﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jzy.DAL.Calendar;
using Jzy.Model;
using Jzy.Model.Calendar;
using System.Data;
using System.Web.UI.WebControls;

using Frame.Lib.Core.User;
using Frame.Lib.Core.Dept;
using Frame.Lib.Core.Base;
using Frame.Lib.Common;
using Frame.Lib.Utilities;

namespace Jzy.BLL.Calendar
{
    public class CalendarBO:CommonOperate<CalendarInfo>
    {
        private CalendarDAL cal = null;

        protected override BaseDAL DAL
        {
            get
            {
                return cal;
            }
        }
        private JoinerDAL joiner = null;
        public CalendarBO()
            : base("Calendar")
        {
            cal = new CalendarDAL();
            joiner = new JoinerDAL();
        }

        #region 保存日程
        /// <summary>
        /// 保存日程
        /// </summary>
        /// <param name="calItem"></param>
        /// <returns></returns>
        public override void Save(CalendarInfo info)
        {
            base.Save(info);

            //保存参与者
            joiner.JoinerType = JoinerType.Dept;
            joiner.Save((int)info.ID, info.JoinerDeptIDs);

            joiner.JoinerType = JoinerType.User;
            joiner.Save((int)info.ID, info.JoinerUserIDs);

        }
        #endregion

        #region 获得一条日程信息
        /// <summary>
        /// 获得一条日程信息
        /// </summary>
        /// <param name="strCalID"></param>
        /// <returns></returns>
        public override CalendarInfo GetInfo(object id)
        {
            if (id == null)
            {
                return new CalendarInfo();
            }

            CalendarInfo info = base.GetInfo(id);
            //加上参与人员
            if (info != null)
            {
                joiner.JoinerType = JoinerType.Dept;
                info.JoinerDeptIDs = joiner.GetJoiner(id);

                joiner.JoinerType = JoinerType.User;
                info.JoinerUserIDs = joiner.GetJoiner(id);
            }

            return info;
        }
        #endregion

        #region 获得我的日程（月、周）
        /// <summary>
        /// 获得我的日程（月、周）
        /// </summary>
        /// <param name="time"></param>
        /// <param name="type"></param>
        /// <param name="strUserID"></param>
        /// <returns></returns>
        public DataTable GetPersonalList(DateTime time, object userID)
        {
            UserBO user = new UserBO();
            UserInfo info = user.GetInfo(userID);
            StringBuilder sbDepts = new StringBuilder();

            DeptBO dept = new DeptBO();
            foreach (int deptID in info.DeptIDs)
            {
                DeptInfo deptInfo = dept.GetInfo(deptID);
                sbDepts.Append(deptID);
                sbDepts.Append(deptInfo.Path);
            }

            List<int> lstAllUpperDeptIDs = StrUtil.SplitToInt(sbDepts.ToString());

            DataTable dt = cal.GetList(time, userID, lstAllUpperDeptIDs);
            return dt;
        }
        #endregion

        #region 获得部门日程（月、周）
        /// <summary>
        /// 获得部门日程（月、周）
        /// </summary>
        /// <param name="time"></param>
        /// <param name="type"></param>
        /// <param name="strDeptID"></param>
        /// <returns></returns>
        public DataTable GetDeptList(DateTime time, int deptID)
        {
            DeptBO dept = new DeptBO();
            DeptInfo info = dept.GetInfo(deptID);
            List<int> lstUpperIDs = StrUtil.SplitToInt(info.Path.ToString());
            List<int> lstSubIDs = dept.GetSubIDs(info.ID);

            DataTable dt = cal.GetList(time, lstUpperIDs, lstSubIDs);

            return dt;
        }
        #endregion

        /// <summary>
        /// 一个人属于多个部门时，看部门日程时需要用些方法
        /// </summary>
        /// <param name="time"></param>
        /// <param name="lstDeptIDs"></param>
        /// <returns></returns>
        public DataTable GetDeptList(DateTime time, List<int> lstDeptIDs)
        {
            DataTable dt = GetDeptList(time, lstDeptIDs[0]);
            List<int> lstCalIDs = new List<int>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                lstCalIDs.Add((int)dr["ID"]);
            }

            //把所属其它各门部的日程加进来
            for (int i = 1; i < lstDeptIDs.Count; i++)
            {
                DataTable tmp = GetDeptList(time, lstDeptIDs[i]);
                foreach (DataRow dr in tmp.Rows)
                {
                    int calID = (int)dr["ID"];
                    if (lstCalIDs.IndexOf(calID) < 0)
                    {
                        dt.ImportRow(dr);
                        lstCalIDs.Add(calID);
                    }
                }
            }
            return dt;
        }

        #region 获得公司日程（月、周）
        /// <summary>
        /// 获得公司日程（月、周）
        /// </summary>
        /// <param name="time"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public DataTable GetCorpList(DateTime time)
        {
            DataTable dt = cal.GetList(time);
            return dt;
        }
        #endregion

        #region 创建一周的DataTable
        /// <summary>
        /// 创建一周的DataTable
        /// </summary>
        /// <returns></returns>
        public DataTable CreateWeek(DateTime dCurr)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("WeekDate");
            dt.Columns.Add("Date",typeof(DateTime));
        
            DateTime dMonday = DateTime.Now.GetMonday(dCurr);
            
            for (int i = 1; i <= 7; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Date"] = dMonday;
                dr["WeekDate"] = ((Weeks)i).ToString() + "<br>" + dMonday.ToShortDateString();
                dMonday = dMonday.AddDays(1);

                dt.Rows.Add(dr);
            }

            return dt;
        }
        #endregion

        #region 创建一月的DataTable
        /// <summary>
        /// 创建一月的DataTable
        /// </summary>
        /// <returns></returns>
        public DataTable CreateMonth(DateTime dCurr)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("Sunday");
            dt.Columns.Add("Monday");
            dt.Columns.Add("Tuesday");
            dt.Columns.Add("Wednesday");
            dt.Columns.Add("Thursday");
            dt.Columns.Add("Friday");
            dt.Columns.Add("Saturday");

            DateTime dFirstDayOfMonth = new DateTime(dCurr.Year, dCurr.Month, 1);//当前时间的1月1日
            int iDayOfWeek = (int)dFirstDayOfMonth.DayOfWeek;//当前时间是星期几

            int iAllDays = iDayOfWeek + DateTime.DaysInMonth(dFirstDayOfMonth.Year, dFirstDayOfMonth.Month);//加上1日之前的总天数

            int iRecordCount = iAllDays / 7;//dt的总记录数,也就是页面显示几行
            if (iAllDays % 7 > 0)
            {
                iRecordCount++;
            }

            DateTime dTmp = dFirstDayOfMonth.AddDays(-iDayOfWeek);
            for (int i = 0; i < iRecordCount; i++)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < 7; j++)
                {
                    dr[j] = dTmp.Day;
                    dTmp = dTmp.AddDays(1);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
        #endregion

        public static int GetCreatorID(int calID)
        {
            int creatorID = CalendarDAL.GetCreatorID(calID);
            return creatorID;
        }      

        public int GetTodayCalendarCount(int userID)
        {
            DataTable dt = this.GetPersonalList(DateTime.Now, userID);

            DateTime start = DateTime.Now.Date;
            DateTime end = DateTime.Now.AddDays(1).Date;

            int count = dt.Select("EndTime >='" + start + "' and StartTime <= '" + end + "'").Length;
            return count;
        }

        /// <summary>
        /// 在管理日程时用于检索
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public DataTable GetList(Dictionary<string, string> condition)
        {
            string strCreatorID = condition["CreatorID"];
            string strDateFrom = condition["DateFrom"];
            string strDateTo = condition["DateTo"];
            string strTypeID = condition["TypeID"];

            string strCondition = "";
            if (strCreatorID != "")
            {
                strCondition += "and CreatorID = " + Math.Abs(int.Parse(strCreatorID)) + " ";
            }

            if (strDateFrom != "")
            {
                strCondition += "and InputTime >='" + strDateFrom + "' ";
            }

            if (strDateTo != "")
            {
                strCondition += "and InputTime <='" + strDateTo + "' ";
            }

            if (strTypeID != "0")
            {
                strCondition += "and TypeID = " + strTypeID;
            }

            if (strCondition.Length > 0)
            {
                strCondition = strCondition.Substring(3);
            }
            //DataTable dt = base.GetList(strCondition);

            //DictBO dict = new DictBO();
            //DataTable calType = dict.GetList(MyCommon.DictItem.CalendarType);
            //Dictionary<int, string> dicCalType = new Dictionary<int, string>(calType.Rows.Count);
            //foreach (DataRow dr in calType.Rows)
            //{
            //    dicCalType.Add((int)dr["ID"], (string)dr["Name"]);
            //}

            //dt.Columns.Add("TypeName", typeof(string));

            //foreach (DataRow dr in dt.Rows)
            //{
            //    dr["TypeName"] = dicCalType[(int)dr["TypeID"]];
            //}
            DataTable dt = new DataTable();


            return dt;
        }

        public class DeptUserSelect
        {
            private DropDownList drpDept;
            private DropDownList drpUser;
            private DeptBO dept;

            public DeptUserSelect(DropDownList drpDept, DropDownList drpUser)
            {
                this.drpDept = drpDept;
                this.drpDept.AutoPostBack = true;

                this.drpUser = drpUser;
                this.drpUser.AutoPostBack = true;
                dept = new DeptBO();
            }

            public void Bind(CalendarLevel calLevel)
            {
                switch (calLevel)
                {
                    case CalendarLevel.Corp:
                        {
                            drpDept.Visible = true;
                            BindDepts(drpDept);
                            drpUser.Visible = true;

                            IEnumerable<UserInfo> users = dept.GetUserList((int)dept.GetRootID());
                            BindUsers(drpUser, users);
                            break;
                        }
                    case CalendarLevel.Dept:
                        {
                            drpDept.Visible = false;

                            drpUser.Visible = true;
                            IEnumerable<UserInfo> dt = dept.GetUserList(AppSession.DeptID);
                            BindUsers(drpUser, dt);
                        }
                        break;
                    case CalendarLevel.User:
                        drpDept.Visible = false;
                        drpUser.Visible = false;
                        break;
                }
            }


            public static void BindUsers(DropDownList drpUsers, IEnumerable<UserInfo> users)
            {
                var info = from user in users
                           select new { user.ID, user.Name };
               
                drpUsers.DataSource = info;
                drpUsers.DataTextField = "Name";
                drpUsers.DataValueField = "ID";
                drpUsers.DataBind();

                drpUsers.Items.Insert(0, new ListItem("全部", "all"));

                drpUsers.SelectedValue = "all";
            }


            private void BindDepts(DropDownList drpDepts)
            {
                DeptBO dept = new DeptBO();
                IEnumerable<DeptInfo> list = dept.GetList(dept.GetRootID());
                drpDepts.DataSource = list;
                drpDepts.DataValueField = "ID";
                drpDepts.DataTextField = "Name";
                drpDepts.DataBind();

                drpDepts.Items.Insert(0, new ListItem("全单位", "all"));
                drpDepts.SelectedValue = "all";

            }
        }

        public DataTable GetCurrentView(CalendarLevel CalLevel, DateTime CurrentTime, DropDownList drpDepts, DropDownList drpUsers)
        {
            DataTable dt = null;
            switch (CalLevel)
            {
                case CalendarLevel.User:
                    dt = GetPersonalList(CurrentTime, AppSession.UserID);
                    break;
                case CalendarLevel.Dept:
                    if (drpUsers.SelectedValue == "all")
                    {
                        dt = GetDeptList(CurrentTime, AppSession.DeptID);
                    }
                    else
                    {
                        dt = GetPersonalList(CurrentTime, drpUsers.SelectedValue);
                    }
                    break;
                case CalendarLevel.Corp:
                    if (drpUsers.SelectedValue != "all")
                    {
                        dt = GetPersonalList(CurrentTime, drpUsers.SelectedValue);
                    }
                    else
                    {
                        if (drpDepts.SelectedValue == "all")
                        {
                            dt = GetCorpList(CurrentTime);
                        }
                        else
                        {
                            dt = GetDeptList(CurrentTime, int.Parse(drpDepts.SelectedValue));
                        }
                    }
                    
                    break;
            }
            return dt;
        }
    }
}
